import { ref } from 'vue'
import { ElNotification } from "element-plus";

const socket = ref(null)
const heartInterval = ref(null) // 心跳定时器
const connectCount = ref(0) // 尝试连接次数

export function initWebsocket(store) {
  if(store) {
    const corpid = store.getters.corpinfo.corpid
    const subid = store.getters.subinfo.subid
    if (corpid && subid) {
      const wsUri = process.env.VUE_APP_WEBSOCKET_URI + '/im/console/channel/msg/' + corpid + '/' + subid
      socket.value = new WebSocket(wsUri)
      socket.value.onerror = websocketOnError
      socket.value.onmessage = websocketOnMessage
      socket.value.onclose = websocketOnClose
      socket.value.onopen = heartCheck
    }
  }
}

function websocketOnError(e) {
  console.log('websocket错误：', e);
}

function websocketOnMessage(e) {
  const data = JSON.parse(e.data)
  if (data.type === "notification") {
    ElNotification({
      title: '系统通知',
      type: 'info',
      dangerouslyUseHTMLString: true,
      message: data.content,
      duration: 0,
      position: 'bottom-right'
    })
  }
}

function websocketOnClose() {
  console.log('websocket连接已关闭...');
}

export function closeWebsocket() {
  if (socket.value) {
    socket.value.close()
    console.log('获取不到用户登录状态，websocket断开连接...');
  }
}

function heartCheck() {
  if (heartInterval.value) {
    clearInterval(heartInterval.value)
  }
  // 尝试连接次数
  connectCount.value = 0
  // 定时发送心跳
  const func = () => {
    if (socket.value.readyState === 1) {
      socket.value.send('ping')
    } else {
      // 连接异常，尝试重新连接，最多5次
      connectCount.value++
      if (connectCount.value <= 5) {
        initWebsocket()
      }
    }
  }
  heartInterval.value = setInterval(func(), 30 * 1000)
}
